﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Xml;
using System.Xml.Linq;
using System.Diagnostics;

namespace Updateapp
{
    public partial class FrmUpdateVersion : Form
    {

        public FrmUpdateVersion()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private void FrmUpdateVersion_Load(object sender, EventArgs e)
        {

            //source下载url
            string source_url = "http://192.168.80.16/cgi-bin/fglccgi/topprod/tiptop/Logistics/";
           string LogisticsFolder = Application.StartupPath;

            //string LogisticsFolder = "C:\\WORK\\项目\\森赫\\成品\\Logistics\\upd";

            //最新版本
            string n_verfile = source_url + "src/ver.txt";
            Uri n_uri = new Uri(n_verfile);
            WebRequest n_req = WebRequest.Create(n_uri);
            WebResponse n_resp = n_req.GetResponse();
            Stream n_stream = n_resp.GetResponseStream();
            StreamReader n_sr = new StreamReader(n_stream);
            string n_str = n_sr.ReadToEnd();
            int updateVersion = 0;
            if (string.IsNullOrEmpty(n_str))
            {
                 updateVersion = 99999;
            }
            else
            {
                 updateVersion = Convert.ToInt32(n_str.Replace("V", "").Replace(".", ""));
            }
            

            
            //当前版本
            string verfile = LogisticsFolder + "\\..\\src\\ver.txt";
            int currentVersion = 0;
            if (System.IO.File.Exists(verfile))
            {
                FileStream filest = new FileStream(verfile, FileMode.Open, FileAccess.ReadWrite);
                StreamReader sr = new StreamReader(filest);
                string strLine = sr.ReadLine();
                sr.Close();
                filest.Close();

                if (string.IsNullOrEmpty(strLine))
                {
                    currentVersion = 0;
                }
                else
                {
                    currentVersion = Convert.ToInt32(strLine.Replace("V", "").Replace(".", ""));
                }
            }
            else
            {
                currentVersion = 0;
            }
            
           
          


            if (updateVersion > currentVersion)//如果需要更新的版本号大于当前版本号则表明需要更新
            {

                    MessageBox.Show("当前版本" + currentVersion.ToString() + " 最新版本" + updateVersion.ToString() + "\n版本已更新,点击确定将下载更新！");
                    string[] fileName = new string[] { "Logistics.application", "Logistics.DataAccess.dll", "Logistics.DataAccess.pdb", "Logistics.exe", "Logistics.exe.config", "Logistics.exe.manifest", "Logistics.Manager.dll", "Logistics.Manager.pdb", "Logistics.Model.dll", "Logistics.Model.pdb", "Logistics.pdb", "Logistics.vshost.application", "Logistics.vshost.exe", "Logistics.vshost.exe.config", "Logistics.vshost.exe.manifest","ver.txt" };
                    updateFileCount = fileName.Length;
                    for (int i = 0; i < fileName.Length; i++)
                    {
                        string l_url = source_url + "/src/" + fileName[i].ToString();
                        string saveFolder = LogisticsFolder + "\\..\\src\\" + fileName[i];
                        DownloadFile(l_url, saveFolder, ProgressBar_Value, null);

                    }

            }
            else
            {
                Process.Start(Application.StartupPath+"\\..\\src\\Logistics.exe");
                System.Environment.Exit(0);
            }
        }
        private void DownloadFile(string url, string savefile, Action<int> downloadProgressChanged, Action downloadFileCompleted)
        {
            WebClient client = new WebClient();
            if (downloadProgressChanged != null)
            {
                client.DownloadProgressChanged += delegate(object sender, DownloadProgressChangedEventArgs e)
                { this.Invoke(downloadProgressChanged, e.ProgressPercentage); };
            }
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(c_DownloadFileCompleted);

            client.DownloadFileAsync(new Uri(url), savefile);

        }
        delegate void Action();

        int updateFileCount = 0;
        void c_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            updateFileCount--;
            if (updateFileCount == 0)
            {
                Console.WriteLine("更新完成！");
                Process.Start(Application.StartupPath + "\\..\\src\\Logistics.exe");
                System.Environment.Exit(0);
            }

        }

        private void ProgressBar_Value(int val)
        {
            progressBar1.Value = val;
            label1.Text = val.ToString() + "%";

        }

        /// <summary>
        /// 获取远程服务器版本号
        /// </summary>
        /// <param name="strURL"></param>
        /// <returns></returns>
        private string GetVersion(string strURL)
        {
            HttpWebRequest request;
            // 创建一个HTTP请求
            request = (HttpWebRequest)WebRequest.Create(strURL);
            HttpWebResponse response;
            response = (HttpWebResponse)request.GetResponse();
            System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string responseText = myreader.ReadToEnd();
            myreader.Close();
            return responseText;
        }

        /// <summary>        
        /// 加载远程XML文档        
        /// </summary>       
        /// <param name="URL"></param>        
        /// <returns></returns>        
        public XDocument LoadXML(string URL)
        {
            //使用rssURL的值建立了一个WebRequest项            
            WebRequest myRequest = WebRequest.Create(URL);
            //WebRequest请求的响应将会被放到一个WebResponse对象myResponse里,然后这个WebResponse对象被用来建立一个流来取出XML的值            
            WebResponse myResponse = myRequest.GetResponse();
            Stream stream = myResponse.GetResponseStream();
            //使用一个XmlDocument对象rssDoc来存储流中的XML内容。XmlDocument对象用来调入XML的内容            
            XDocument doc = new XDocument();
            doc = XDocument.Load(stream);
            return doc;
        }

        public class VersionInfo
        {
            private string versionNo;

            public string VersionNo
            {
                get { return versionNo; }
                set { versionNo = value; }
            }

            private string url;

            public string Url
            {
                get { return url; }
                set { url = value; }
            }
        }


        public VersionInfo GetVersionInfo(XDocument doc)
        {
            VersionInfo version = new VersionInfo();
            try
            {
                IEnumerable<XElement> userElement = (from el in doc.Element("Data").Elements("Info") select el);
                foreach (XElement el in userElement)
                {
                    version.VersionNo = (string)el.Attribute("version");
                    version.Url = (string)el.Attribute("url");
                }
            }
            catch (Exception error)
            {
                throw new Exception(error.Message);
            }
            return version;
        }
    }
}
